package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.CmpClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestPram;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private CmpClient cmpClient;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderLogisticsService orderLogisticsService;
    @Autowired
    private UserClient userClient;

    @Override
    @Transactional
    public Long createOrder(RequestPram requestPram) {
        Item item = cmpClient.getById(requestPram.getItemId());
        long total = item.getPrice() * requestPram.getNum();
        Order order = Order.builder().totalFee(total).status(1).paymentType(requestPram.getPaymentType()).build();
        this.save(order);
        OrderDetail orderDetail = OrderDetail.builder()
                .name(item.getName())
                .spec(item.getSpec())
                .price(item.getPrice())
                .num(requestPram.getNum())
                .itemId(item.getId())
                .image(item.getImage())
                .orderId(order.getId()).build();
        orderDetailService.save(orderDetail);
        Long addressId = requestPram.getAddressId();
        OrderLogistics orderLogistics = OrderLogistics.builder().orderId(order.getId()).build();
        Address address = userClient.findAddressById(addressId);
        BeanUtils.copyProperties(address, orderLogistics);
        orderLogisticsService.save(orderLogistics);
        try {
            cmpClient.updateStock(requestPram.getItemId(), requestPram.getNum());
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }

        return order.getId();
    }
}
